// merge5.hxx


#ifndef _BLOGS_MERGE5
#define _BLOGS_MERGE5


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"


namespace blogs
{


class Merge5
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __merge__(Array<_T> & a, int lo, int mi, int hi, Array<_T> & aux)
    {
        int i = lo, j = hi;
        for (int k = lo; k <= mi; ++k)
            aux[k] = a[k];
        for (int k = mi+1; k <= hi; ++k)
            aux[k] = a[hi - (k - (mi+1))];
        for (int k = lo; i <= j; ++k)
            if (__less__(aux[i], aux[j])) a[k] = aux[i++];
            else                          a[k] = aux[j--];
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        int N = a.size();
        Array<_T> aux = Array<_T>(N);
        for (int k = 0; k < N; ++k)
            aux[k] = a[k];
        int lo = 0, mi = 0, hi = 1;
        while (hi < N) {
            __merge__(a, lo, mi, hi, aux);
            mi = hi++;
            while (hi < N-1 && __less__(a[hi], a[hi+1])) ++hi;
        }
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

